// 认关路由配置

const Router = require('@koa/router');
const mongoose = require('mongoose');
const InviteCodeModel = mongoose.model('InviteCode');
const { v4: uuidv4 } = require('uuid');

const router = new Router({
  prefix: '/invite',
});

// 添加注册码
router.get('/add', async (ctx) => {
  const inviteCode = new InviteCodeModel({
    code: uuidv4(),
    user: '',
  });
  const res = await inviteCode.save();
  ctx.body = {
    msg: '添加邀请码成功',
    code: 1,
    data: res,
  };
});

router.get('/list', async (ctx) => {
  let { page, size } = ctx.query;
  page = Number(page);
  size = Number(size);
  const list = await InviteCodeModel.find()
    .sort({ _id: -1 })
    .skip((page - 1) * size)
    .limit(size)
    .exec();
  const total = await InviteCodeModel.find().countDocuments().exec();
  ctx.body = {
    msg: '获取邀请码列表成功',
    code: 1,
    data: {
      list,
      total,
    },
  };
});

router.delete('/:id', async (ctx) => {
  const { id } = ctx.params;
  console.log(id);
  const findone = await InviteCodeModel.find({ _id: id }).exec();
  if (!findone.user) {
    ctx.body = {
      msg: '删除邀请失败，邀请码已被使用',
      code: 0,
      data: null,
    };
    return;
  }
  ctx.body = {
    msg: '删除邀请码成功',
    code: 1,
    data: null,
  };
});

module.exports = router;
